#include "UdpServer.hpp"
#include <pthread.h>
void Usage(const std::string &s)
{
    std::cout << "\n\rUsage: " << s << " serverip serverport\n"
              << std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void *recvr_routine(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[SIZE];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t n = recvfrom(td->sockfd, buffer, SIZE - 1, 0, (struct sockaddr *)&temp, &len);
        if (n < 0)
        {
            exit(2);
        }
        buffer[n] = 0;
        std::cout << buffer << std::endl;
    }
}

void *sender_routine(void *args)
{
    ThreadData* td = static_cast<ThreadData*> (args);
    std::string message;
    socklen_t len = sizeof(td->server);
    std::string welcome = td->serverip;
    welcome+="coming";
    sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->server), len);
    while(true)
    {
        message[0] = 0;
        std::cout << "please Enter# ";
        std::cin >> message;
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(td->server), len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    td.server.sin_port = htons(serverport);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        exit(1);
    }
    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recvr_routine, &td);
    pthread_create(&sender, nullptr, sender_routine, &td);
    pthread_join(recvr,nullptr);
    pthread_join(sender, nullptr);
    
    close(td.sockfd);
    return 0;
}